package com.didispace;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync
@RefreshScope
@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		new SpringApplicationBuilder(Application.class).web(true).run(args);
	}

	@Autowired
	ConfigurableApplicationContext context;
	@Value("${from}")
	private String from;
	
	@Autowired
	ApplicationContext context1;
	@Autowired
	private MyBean myBean;
	@Autowired
	private MyBean2 myBean2;
	@Autowired
	private User user;
//	@Bean
//	public User getUser(){
//		System.out.println("initial user");
//		User user = new User();
//		user.setName("hello");
//		user.setAge(20);
//		return user;
//		
//	}
//	
//	@Bean
//    public MyBean mybean(){
//		System.out.println("initial mybean");
//    	MyBean mybean = new MyBean();
//    	mybean.setTest(from+"eshin");
//		return mybean;
//    }
	@Async
	@EventListener(RefreshScopeRefreshedEvent.class)
    public void refreshBean(RefreshScopeRefreshedEvent event){
//		User user = (User)context.getBean("user");
//		System.out.println("refresh "+myBean.test);
		System.out.println("event happened:"+event);
		System.out.println(context.getBeanFactory().getBeanDefinitionNames().toString());
		MyBean bean = context.getBeanFactory().getBean(com.didispace.MyBean.class);
		MyBean2 bean2 = context.getBeanFactory().getBean(com.didispace.MyBean2.class);
		context.getBeanFactory().initializeBean(bean, "mybean");
		context.getBean(com.didispace.MyBean.class).doing();
//		BeanUtils.instantiate(com.didispace.MyBean.class);
//		bean.doing();
		bean2.doing();
//    	context.refresh();
    }
}
